package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.dao.jdbc.JdbcDao;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joint.base.entity.Company;
import com.joint.base.entity.LocationEntity;
import com.joint.base.entity.Users;
import com.joint.base.entity.system.Locations;
import com.joint.base.parent.NameEntity;
import com.joint.base.service.LocationEntityService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.ProInfo;
import com.joint.core.entity.ProLeave;
import com.joint.core.entity.ProSignIn;
import com.joint.core.service.ProAttendService;
import com.joint.core.service.ProInfoService;
import com.joint.core.service.ProLeaveService;
import com.joint.core.service.ProSignInService;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.hssf.util.Region;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by amin on 2015/3/9.
 */
@ParentPackage("com")
public class AjaxCalendarAction extends BaseAdminAction {
    @Resource
    private ProSignInService proSignInService;
    @Resource
    private UsersService usersService;
    @Resource
    private ProInfoService proInfoService;
    @Resource
    private ProLeaveService proLeaveService;
    @Resource
    private LocationEntityService locationEntityService;
    @Resource
    private ProAttendService proAttendService;
    @Resource
    private JdbcDao jdbcDao;

    private String proInfoId;
    private String exportProInfoId;
    private String year;
    private String month;
    private String usersId;
    private String realPath;

    private ProSignIn proSignIn;
    private ProLeave proLeave;
    private String proArea;
    private String type;
    private String address;

    private long start;
    private long end;
    private Map<String,Object> mapData;

    public String dialog(){
        if(StringUtils.equals("prosign",type)){
            proSignIn=proSignInService.get(keyId);
            ProInfo proInfo = proSignIn.getProInfo();
            proArea = proInfo.getProvince()+proInfo.getCity()+proInfo.getCounty();
            Locations locations=locationsService.get(proSignIn.getLocationId());
            LocationEntity locationEntity=locationEntityService.getLocationByTargetId(locations.getId());
            if(locationEntity!=null){
                address=locationsService.getAddress(locations);
            }else{
                address=proSignIn.getAddress();
            }
        }
        if(StringUtils.equals("proleave",type)){
            proLeave=proLeaveService.get(keyId);
        }

        return "dialog";
    }

    public Map<String,Object> fillMap(NameEntity entity){
        ProLeave proLeave = null;
        if(entity instanceof ProSignIn){
            proSignIn = (ProSignIn) entity;
        } else {
            proLeave = (ProLeave) entity;
        }
        Boolean flag = entity instanceof ProSignIn;
        mapData=Maps.newHashMap();
        mapData.put("id",entity.getId());
        //LogUtil.info(proLeave.getProInfo().getName());
        mapData.put("title","[项目名]"+(flag==true?proSignIn.getProInfo().getName():proLeave.getProInfo().getName()));
        mapData.put("description",(flag==true?"[签到人]":"[请假人]")+(flag==true?proSignIn.getCreater().getName():proLeave.getCreater().getName()));
        mapData.put("linkUrl","ajax-calendar!dialog.action?keyId="+entity.getId()+"&type="+(flag==true?"prosign":"proleave"));
        mapData.put("allDay",true);
        mapData.put("start", DataUtil.DateTimeToString(flag == true ? entity.getCreateDate() : proLeave.getLeaveDate()));
        if(flag){
            mapData.put("className",proSignIn.getStatus()==1?"['event', 'bg-color-greenLight']":"['event', 'bg-color-orange']");
        }else {
            mapData.put("className","['event', 'bg-color-red']");
        }
        mapData.put("icon","");
        mapData.put("end", DataUtil.DateTimeToString(flag == true ? entity.getCreateDate() : proLeave.getLeaveDate()));
        return mapData;
    }


    /**
    * 考勤报表导出
    * dqf创建
    * 2015-8-3
    * */
    public String exportFile(){
        try{
            HSSFWorkbook wb = new HSSFWorkbook();
            Company company = usersService.getCompanyByUser();
            String theme = "人员考勤表";
            String title = company.getName()+year+"年"+month+"月考勤报表";
            if (StringUtils.isNotEmpty(exportProInfoId)){
                theme = "项目考勤表";
            }
            HSSFSheet sheet = wb.createSheet(theme);
            sheet.addMergedRegion(new Region(0,(short)0,0,(short)33));
            sheet.addMergedRegion(new Region(1,(short)0,1,(short)3));
            sheet.addMergedRegion(new Region(1,(short)4,1,(short)33));
            HSSFCellStyle title_style = wb.createCellStyle();
            title_style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            title_style.setBorderRight((short)1);
            title_style.setBorderLeft((short)1);
            title_style.setBorderBottom((short)1);
            title_style.setBorderTop((short)1);
            HSSFFont headerFont = (HSSFFont) wb.createFont();
            headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            //headerFont.setFontName("Times New Roman");
            headerFont.setFontHeightInPoints((short) 12);
            title_style.setFont(headerFont);


            //行号
            int row_num = 0;
            //标题行
            HSSFRow title_row = sheet.createRow(row_num++);
            //副标题行
            HSSFRow subtitle_row = sheet.createRow(row_num++);
            for (int i=0;i<34;i++){
                title_row.createCell(i).setCellStyle(title_style);
                subtitle_row.createCell(i).setCellStyle(title_style);
            }

            title_row.getCell(0).setCellValue(title);
            subtitle_row.getCell(0).setCellValue(month + "月");
            if (StringUtils.isNotEmpty(exportProInfoId)){
                subtitle_row.getCell(4).setCellValue(proInfoService.get(exportProInfoId).getName());
            }

            //表头行
            HSSFCellStyle table_style = wb.createCellStyle();
            table_style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            table_style.setWrapText(true);
            table_style.setBorderRight((short)1);
            table_style.setBorderLeft((short)1);
            table_style.setBorderBottom((short)1);
            table_style.setBorderTop((short)1);
            HSSFFont tableFont = (HSSFFont) wb.createFont();
            tableFont.setFontHeightInPoints((short) 8);
            table_style.setFont(tableFont);

            HSSFRow table_row = sheet.createRow(row_num++);
            table_row.createCell(0).setCellValue(new HSSFRichTextString("        日期 人员"));
            table_row.getCell(0).setCellStyle(table_style);
            //画斜线
            HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
            HSSFClientAnchor a = new HSSFClientAnchor(0, 0, 1023, 255, (short)0, 2, (short)0, 2);
            HSSFSimpleShape shape1 = patriarch.createSimpleShape(a);
            shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
            shape1.setLineStyle(HSSFSimpleShape.LINESTYLE_SOLID);

            for (int i=1;i<=31;i++){
                table_row.createCell(i).setCellValue(i+"日");
                table_row.getCell(i).setCellStyle(table_style);
            }
            table_row.createCell(32).setCellValue("总计出勤");
            table_row.getCell(32).setCellStyle(table_style);
            table_row.createCell(33).setCellValue("异常次数");
            table_row.getCell(33).setCellStyle(table_style);

            //查询的人员列表
            List<Users> usersList = new ArrayList<>();
            if (StringUtils.isEmpty(exportProInfoId)){
                usersList = (List<Users>) usersService.findByPagerAndCompany(new Pager(0),null,company,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList();
            } else {
                ProInfo p = proInfoService.get(exportProInfoId);
                usersList.add(p.getChief());
                Set<Users> tmp = p.getGroup();
                for (Users u:tmp){
                    usersList.add(u);
                }
            }

            //计算查询时间范围
            Calendar cd = Calendar.getInstance();
            if (StringUtils.isNotEmpty(year) && StringUtils.isNotEmpty(month)){
                cd.set(Calendar.MONTH, Integer.parseInt(month)-1);
                cd.set(Calendar.YEAR, Integer.parseInt(year));
            }
            cd.set(Calendar.DATE, 1);
            cd.roll(Calendar.DATE, -1);
            int all_Date = cd.get(Calendar.DATE);    //得到当月的天数

            //设置数据区样式
            HSSFCellStyle body_style = wb.createCellStyle();
            body_style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            body_style.setBorderRight((short)1);
            body_style.setBorderLeft((short)1);
            body_style.setBorderBottom((short)1);
            body_style.setBorderTop((short)1);

            HSSFCellStyle body_style_1 = wb.createCellStyle();
            body_style_1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            body_style_1.setFillForegroundColor(HSSFColor.YELLOW.index);
            body_style_1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            body_style_1.setBorderRight((short)1);
            body_style_1.setBorderLeft((short)1);
            body_style_1.setBorderBottom((short)1);
            body_style_1.setBorderTop((short)1);

            String dateHeader = year+"-"+month+"-";
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (Users thisUser :usersList){
                HSSFRow this_row = sheet.createRow(row_num++);
                this_row.createCell(0).setCellValue(thisUser.getName());
                this_row.getCell(0).setCellStyle(body_style);

                //查询与当前用户相关的所有项目
                List<ProInfo> proInfoList = new ArrayList<ProInfo>();
                if (StringUtils.isNotEmpty(exportProInfoId)){
                    proInfoList.add(proInfoService.get(exportProInfoId));
                } else {
                    proInfoList = (List<ProInfo>) proInfoService.findByPagerAndUsersRelated(new Pager(0),thisUser,company,null).getList();
                }

                float final_all = 0f; //总计签到考勤数
                Long d_error_num = new Long(0);  //异常签到总次数
                for (int d=1;d<=all_Date;d++){
                    Date thisDate = sdf.parse(dateHeader+d);
                    boolean flag = false;
                    float d_count = 0f;   //考勤记数
                    //循环查询该用户的所有项目
                    for (ProInfo p:proInfoList){
                        //判断项目是否在当天有效
                        Date start = new Date(p.getStart().getTime());
                        Date end = p.getEnd()==null?thisDate:new Date(p.getEnd().getTime());
                        if (!(start.getTime()<=thisDate.getTime() && end.getTime()>=thisDate.getTime())){
                            continue;
                        }

                        //查询考勤点
                        int need_num = proAttendService.findByPagerAndProInfo(new Pager(0),p,new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList().size();
                        if (need_num == 0){
                            continue;
                        }

                        //查签到次数
                        Long sign_num = new Long(0);
                        String query_sql = "SELECT status FROM ec_prosignin WHERE createDate >= :date1 and createDate <= :date2 and state= 'Enable' and proInfo_id= :proInfoId and creater_id= :createrId ";
                        Map<String,String> filter = new HashMap<String,String>();
                        filter.put("date1",sdf1.format(thisDate));
                        thisDate.setHours(23);
                        thisDate.setMinutes(59);
                        thisDate.setSeconds(59);
                        filter.put("date2",sdf1.format(thisDate));
                        filter.put("proInfoId",p.getId());
                        filter.put("createrId",thisUser.getId());
                        List<Map<String, Object>> all_ListMap = jdbcDao.findForListMap(query_sql,filter);//签到次数

                        if(null != all_ListMap && all_ListMap.size()>0) {
                            sign_num = (long)all_ListMap.size();
                            for (Map sm:all_ListMap){
                               if (sm.get("status") == 0){
                                   d_error_num ++;
                                   flag = true;
                               }
                            }
                        }

                        d_count += (float)sign_num/need_num;

                        //异常签到次数
//                        query_sql += " and status=0";
//                        List<Map<String, Object>> error_ListMap = jdbcDao.findForListMap(query_sql,filter);
//                        if(null != error_ListMap && error_ListMap.size()>0) {
//                            Map lMap = error_ListMap.get(0);
//                            Long tmp = (Long)lMap.get("counts");
//                            if (tmp > 0){
//                                flag = true;
//                            }
//                            d_error_num += tmp;
//                        }

                        thisDate.setHours(0);
                        thisDate.setMinutes(0);
                        thisDate.setSeconds(0);
                    }

                    if (d_count > 1f){
                        d_count = 1f;
                    } else {
                        d_count = Math.round(d_count*100f)/100f;
                    }
                    final_all += d_count;
                    this_row.createCell(d).setCellValue(d_count);
                    if (flag){
                        this_row.getCell(d).setCellStyle(body_style_1);
                    }else{
                        this_row.getCell(d).setCellStyle(body_style);
                    }
                }

                for (int ld=all_Date+1;ld<=31;ld++){
                    this_row.createCell(ld).setCellValue("-");
                    this_row.getCell(ld).setCellStyle(body_style);
                }

                this_row.createCell(32).setCellValue(final_all);
                this_row.getCell(32).setCellStyle(body_style);
                this_row.createCell(33).setCellValue(d_error_num);
                this_row.getCell(33).setCellStyle(body_style);
            }

            //保存文档
            //ResourceLoader resourceLoader = new DefaultResourceLoader();

            String path = "/resource/excel/" +year+"年"+ month + "月考勤报表.xls";
            realPath = ServletActionContext.getServletContext().getRealPath(path);
            FileOutputStream fops = new FileOutputStream(realPath);
            wb.write(fops);
            fops.close();

        }catch (Exception e){
            return ajaxHtmlCallback("400", "导出错误","操作状态");
        }


        return ajaxText(realPath);

    }

    public void downloadFile(){
        try {
            InputStream inputStream = new FileInputStream(realPath);

            OutputStream out = null;
            HttpServletResponse response = getTheResponse();
            response.setContentType("text/plain;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("content-disposition", "attachment;filename=" + new String(("考勤报表.xls").getBytes(), "ISO8859-1"));
            out = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int i = -1;
            while ((i = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, i);
            }
            out.flush();
            out.close();
            inputStream.close();

        }catch (Exception e){
            System.out.println("download file error");
        }
    }

    /**
     * @updated by zhucx
     * @date 2015-7-14
     * 增加正常，迟到，反馈类型
     * @return
     * @throws ParseException
     */
    public String taskData() throws ParseException {
        List<JSONObject> dataRows = Lists.newArrayList();

        List<JSONObject> rows = Lists.newArrayList();
        Company company=usersService.getCompanyByUser();
        Map<String,Object> rmap= Maps.newHashMap();
        List<ProSignIn> proSignInList=null;
        List<ProLeave> proLeaveList=null;

        pager=new Pager(0);
        Pager leavePager = new Pager(0);


        Date startDate = new Date(start);
        Date endDate = new Date(end);

        rmap.put("state", BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(proInfoId)) rmap.put("proInfo.id",proInfoId);
        if(StringUtils.isNotEmpty(usersId)) rmap.put("creater.id",usersId);
        if(!type.equals("3")) {
            if(type.equals("1")){
                rmap.put("status",1);
                leavePager = new Pager();
            }else if(type.equals("2")){
                rmap.put("status",0);
                leavePager = new Pager();
            }else{
                leavePager = proLeaveService.findByPagerAndCompany(leavePager,"leaveDate",startDate,endDate,null,company,rmap);
            }
            pager= proSignInService.findByPagerAndCompany(pager,"createDate",startDate,endDate,null,company,rmap);
        }else{
            leavePager = proLeaveService.findByPagerAndCompany(leavePager, "leaveDate", startDate, endDate, null, company, rmap);
            pager=new Pager();
        }
        if(StringUtils.isEmpty(proInfoId) && StringUtils.isEmpty(usersId)){
            pager=new Pager();
            leavePager = new Pager();
        }

        proSignInList = (List<ProSignIn>) (pager.getTotalCount()>0?pager.getList():Lists.newArrayList());
        proLeaveList = (List<ProLeave>) (leavePager.getTotalCount()>0?leavePager.getList():Lists.newArrayList());

        //LogUtil.info("{ proSignInList }"+proSignInList.size());
        for(ProSignIn proSignIn:proSignInList){
            dataRows.add(JSONObject.fromObject(fillMap(proSignIn)));
        }
        for(ProLeave proLeave:proLeaveList){
            dataRows.add(JSONObject.fromObject(fillMap(proLeave)));
        }

        return ajaxJson(JSONArray.fromObject(dataRows).toString());
    }

    public long getStart() {
        return start;
    }

    public void setStart(long start) {
        this.start = start;
    }

    public long getEnd() {
        return end;
    }

    public void setEnd(long end) {
        this.end = end;
    }

    public String getUsersId() {
        return usersId;
    }

    public void setUsersId(String usersId) {
        this.usersId = usersId;
    }

    public String getProInfoId() {
        return proInfoId;
    }

    public void setProInfoId(String proInfoId) {
        this.proInfoId = proInfoId;
    }

    public ProSignIn getProSignIn() {
        return proSignIn;
    }

    public void setProSignIn(ProSignIn proSignIn) {
        this.proSignIn = proSignIn;
    }

    public String getProArea() {
        return proArea;
    }

    public void setProArea(String proArea) {
        this.proArea = proArea;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public ProLeave getProLeave() {
        return proLeave;
    }

    public void setProLeave(ProLeave proLeave) {
        this.proLeave = proLeave;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getExportProInfoId() {
        return exportProInfoId;
    }

    public void setExportProInfoId(String exportProInfoId) {
        this.exportProInfoId = exportProInfoId;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getMonth() {
        return month;
    }

    public void setMonth(String month) {
        this.month = month;
    }

    public String getRealPath() {
        return realPath;
    }

    public void setRealPath(String realPath) {
        this.realPath = realPath;
    }
}
